package com.reggie.configuration.common;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

/**
 * 因为这个类要传递的不是内存数据，是硬盘实际储存的数据，所以不能返回内存数据了
 */

@RestController
@RequestMapping("/common")
@Slf4j
public class PictureController {

    //@Value("${path}")
    private static final String path = "/Users/mac/Pictures/reggieDishPicture/picture/";

    /**
     * 将文件上传到服务端，然后服务端进行本地存储
     *
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/upload")
    public Result<String> uploadPicture(MultipartFile file) throws Exception {
        File file1 = new File(path);
        if (!file1.exists()) {
            file1.mkdirs();
        }

        String Picture = file.getOriginalFilename();
        long size = file.getSize();
        log.info("文件名为:{}，文件大小为:{}", Picture, size);

        //保存文件，将名称设为唯一的UUID
        String fileName = UUID.randomUUID().toString().replace("-", "");
        //获取文件后缀
        String substring = Picture.substring(Picture.lastIndexOf("."));

        //两种方式进行保存，一种是用IO流保存
//        FileOutputStream outputStream = new FileOutputStream(path+fileName+substring);
        //将两个流合并
//        IOUtils.copy(file.getInputStream(),outputStream);

        //TODO 第二种方式就是比较简单的一种写法 目前不太理解
        file.transferTo(new File(path + fileName + substring));

        //这里如果上传成功需要返回更新后的文件名
        return Result.success(fileName + substring);
    }

    @RequestMapping("/download")
    public void downloadPicture(@RequestParam("name") String name, HttpServletResponse response) throws Exception {
        //这条命令是找图片所在位置
        FileInputStream inputStream = new FileInputStream(path + name);
        log.info("文件名为:{}", name);
        //这是对两个流进行合流
        response.setContentType("text/json;charset=UTF-8");
        IOUtils.copy(inputStream, response.getOutputStream());
    }

}
